package com.time.tell.the.truth.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.DefaultEventExecutor;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadFactory;

@Slf4j
public class Server {
  public void start() {
    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup(3);
    DefaultEventExecutorGroup bizGroup = new DefaultEventExecutorGroup(16);
    try {
      ServerBootstrap serverBootstrap = new ServerBootstrap()
          .group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .childOption(ChannelOption.SO_KEEPALIVE, true)
          .handler(new ServerChannelHandler())
          .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) {
              ch.pipeline().addLast(bizGroup, new ParseCmdHandler());
              ch.pipeline().addLast(new ExecuteCmdHandler());
              ch.pipeline().addFirst(new RespondHandler());
            }
          });

      ChannelFuture channelFuture = serverBootstrap.bind(8765).sync();
      log.info("Server started on port 8765");

      channelFuture.channel().closeFuture().sync();
    } catch (InterruptedException e) {
      log.error("start server error", e);
      Thread.currentThread().interrupt();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
      bizGroup.shutdownGracefully();
    }
  }

  public static void main(String[] args) {
    new Server().start();
  }
}
